import 'dart:convert';

import '../../generated/json/base/json_convert_content.dart';

///基础的数据格式
class HttpResponse {
  int code = 1; //：0 正常  1：错误
  String msg = ""; //信息

  HttpResponse();

  HttpResponse fromJson(Map<String, dynamic> json) {
    if (json['code'] != null) {
      code = json['code'] is String
          ? int.tryParse(json['code'])
          : json['code'].toInt();
    }
    if (json['msg'] != null) {
      msg = json['msg'].toString();
    }
    return this;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['code'] = code;
    data['msg'] = msg;
    return data;
  }

  bool get isSuccess => code == 0;
}

class HttpResult<T> extends HttpResponse {
  late T data;

  @override
  HttpResult<T> fromJson(Map<String, dynamic> json) {
    super.fromJson(json);
    if (json["data"] != null) {
      data = JsonConvert.fromJsonAsT<T>(json['data']) as T;
    } else if (json["list"] != null) {
      data = JsonConvert.fromJsonAsT<T>(json['list']) as T;
    }
    return this;
  }

  @override
  Map<String, dynamic> toJson() {
    final Map<String, dynamic> result = super.toJson();
    result['data'] = jsonEncode(data);
    return result;
  }
}

class HttpPageResult<T> extends HttpResult<T> {
  /// 当前是服务器数据的第几页
  int currentPage = 1;

  /// 一共多少页
  int pageCount = -1;

  @override
  HttpPageResult<T> fromJson(Map<String, dynamic> json) {
    super.fromJson(json);
    if (json["currentPage"] != null) {
      currentPage = json['currentPage'] is String
          ? int.tryParse(json['currentPage'])
          : json['currentPage'].toInt();
    }
    if (json["pageCount"] != null) {
      pageCount = json['pageCount'] is String
          ? int.tryParse(json['pageCount'])
          : json['pageCount'].toInt();
    }
    return this;
  }

  @override
  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = super.toJson();
    data['pageCount'] = currentPage;
    data['currentPage'] = currentPage;
    return data;
  }
}
